# -*- coding: utf-8 -*-
import hashlib
import hmac
import json
from binascii import b2a_hex
from collections import OrderedDict

import requests
from Crypto.Cipher import AES as _AES

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'CD0002232': {  # cpay支付宝到银行卡 支付宝h5 2.7% 100-20000 zs
        'gateway': 'http://open.cpay.life/api/v2_tran',
        'query_gateway': 'http://open.cpay.life/api/alipay_order/detail',
        'pub_key': "5bf9214fac7da4136e4c1d0f",
        'pri_key': "f220d92b3a2b28209a664fd7ba789ae7",
    },
    'CD0002459': {  # cpay支付宝到银行卡 支付宝h5 2.7% 100-20000 witch
        'gateway': 'http://open.cpay.life/api/v2_tran',
        'query_gateway': 'http://open.cpay.life/api/alipay_order/detail',
        'pub_key': "5c1f20a1ac7da403ad4c5b32",
        'pri_key': "cfcdedc54b3512d8da221d5cf67d96db",
    },
}


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_cpay_pub_key(mch_id):
    return APP_CONF[mch_id]['pub_key']


def _get_cpay_pri_key(mch_id):
    return APP_CONF[mch_id]['pri_key']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def encode(key, text):
    if not isinstance(text, str) and not isinstance(text, unicode):
        text = json.dumps(text)
    cryptor = _AES.new(key, _AES.MODE_ECB, b'3eddc41dd41239c8')
    length = 16
    count = len(text)
    if count < length:
        add = (length - count)
        # \0 backspace
        text = text + ('\0' * add)
    elif count > length and count % length != 0:
        add = (length - (count % length))
        text = text + ('\0' * add)
    ciphertext = cryptor.encrypt(text)

    return b2a_hex(ciphertext)


def generate_sign(secret_key, parameter_dict):
    """
    加密
    :param secret_key:
    :param parameter_dict:
    :return:
    """
    mapping = {}
    for k, v in parameter_dict.items():
        mapping[k.lower()] = v

    keys = [k.lower() for k in mapping.keys()]
    keys.sort()
    s = "&".join(["%s=%s" % (k, mapping[k]) for k in keys])
    s = encode(secret_key, s)
    s = hmac.HMAC(secret_key.encode("u8"), s).hexdigest()
    return s


def verify_notify_sign(params, key, token):
    _LOGGER.info('cpayalipay2bank params: %s, key: %s, token: %s', params, key, token)
    calculated_sign = generate_sign(key, params)
    if token != calculated_sign:
        _LOGGER.info("cpayalipay2bank token: %s, calculated sign: %s", token, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'alipay':
        return 'cib'
    return 'cib'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    parameter_dict = OrderedDict((
        ('psd_order_id', str(pay.id)),
        ('psd_order_time', local_now().strftime('%Y%m%d%H%M%S')),
        ('order_amount', str(int(pay_amount) * 100)),
        ('order_source', 2),  # 1 PC 2 手机
        ('pay_type', _get_pay_type(service)),
    ))
    token = generate_sign(_get_cpay_pri_key(app_id), parameter_dict)
    _LOGGER.info("cpayalipay2bank create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded', 'appkey': _get_cpay_pub_key(app_id), 'token': token}
    _LOGGER.info('cpayalipay2bank header: %s', headers)
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5, verify=False)
    _LOGGER.info("cpayalipay2bank create rsp : %s", response.text)
    data = json.loads(response.text)
    if data['data'].get('cpay_order_id', None):
        order_db.fill_third_id(pay.id, data['data']['cpay_order_id'])
    return {'charge_info': data['data']['redirect_url']}


def check_notify_sign(request, app_id):
    pri_key = _get_cpay_pri_key(app_id)
    _LOGGER.info("cpayalipay2bank notify data: %s", request.body)
    data = dict(request.POST.iteritems())
    token = request.META.get('HTTP_TOKEN')
    verify_notify_sign(data, pri_key, token)
    pay_id = data['psd_order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('cpayalipay2bank event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'success'
    trade_no = data['cpay_order_id']
    total_fee = float(data['order_amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success' and total_fee > 0.0:
        _LOGGER.info('cpayalipay2bank check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pass
